package org.dreamwork.cai.spring;

import org.dreamwork.cai.io.IRouteBroadcaster;
import org.dreamwork.cai.io.impl.UdpRouteBroadcaster;
import org.dreamwork.cai.proxy.IServiceResolver;
import org.dreamwork.cai.srf.ServiceRouteFrame;
import org.dreamwork.cai.srf.ServiceRouteTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class SpringUdpRouteBroadcasterBridge implements IRouteBroadcaster {
    private UdpRouteBroadcaster broadcaster;
    private ServiceRouteTable table;
    private IServiceResolver resolver;
    private int senderPort;

/*
    public SpringUdpRouteBroadcasterBridge (@Autowired IServiceResolver resolver, @Autowired ServiceRouteTable table) {
        this.resolver = resolver;

    }
*/

    @Autowired
    public void setTable (ServiceRouteTable table) {
        this.table = table;
    }

    @Autowired
    public void setResolver (IServiceResolver resolver) {
        this.resolver = resolver;
    }

    public void setSenderPort (int senderPort) {
        this.senderPort = senderPort;
    }

    /*
    private void init () {
        ServiceRouteFrame srf = table.get (resolver.getLocalNamespace ());
        broadcaster = new UdpRouteBroadcaster (resolver, srf.udpPort);
    }
*/

    @Override
    public void update (ServiceRouteFrame frame) throws IOException {
        broadcaster.update (frame);
    }

    @Override
    public void heartbeat () throws IOException {
        broadcaster.heartbeat ();
    }

    @Override
    public void withdrawn () throws IOException {
        broadcaster.withdrawn ();
    }

    @Override
    public void bind (int port) throws IOException {
        broadcaster = new UdpRouteBroadcaster (resolver, senderPort);
        broadcaster.setLocalNamespace (resolver.getLocalNamespace ());
        broadcaster.bind (port);
    }

    @Override
    public void unbind () throws IOException {
        broadcaster.unbind ();
    }
}